import { ref } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { showToast } from '@nutui/nutui'

let socket: any = null
let heart: any = null
let connected = ref<boolean>(false)

const connect = (url: string) => {
  if ('WebSocket' in window) {
    const store = useAuthStore()
    socket = new WebSocket(url + '?Authorization=' + store.userToken)
  } else {
    showToast.fail('不支持WebSocket')
    return false
  }

  socket.onerror = (e: any) => {
    console.log('websocket error', e)
  }

  socket.onopen = (e: any) => {
    console.log('websocket connected', e)
    connected.value = true
  }

  socket.onclose = (e: any) => {
    console.log(`websocket closed, code: ${e.code}, rason: ${e.reason}`)
    connected.value = false
  }

  socket.onmessage = (e: any) => {
    console.log(`websocket message: ${e.data}`)
  }
  return true
}

const close = () => {
  if (socket) {
    socket.close()
    socket = null
  }
  connected.value = false
  clearHeart()
}

const setHeart = (lessonId: number, chapterId: number, heartTime: number) => {
  if (heart) {
    return
  }
  heart = setTimeout(() => {
    sendHeart(lessonId, chapterId)
    clearHeart()
    setHeart(lessonId, chapterId, heartTime)
  }, heartTime)
}

const clearHeart = () => {
  if (heart) {
    clearTimeout(heart)
    heart = null
  }
}

const sendMessage = (msg: string) => {
  if (!socket) return
  let round = 0
  setTimeout(() => {
    if (connected.value) {
      console.log('send msg', msg)
      socket.send(msg)
    } else {
      if (round <= 5) {
        //发送尝试5次
        sendMessage(msg)
        round++
      }
    }
  }, 500)
}

const sendHeart = (lessonId: number, chapterId: number) => {
  const msg = {
    type: 1,
    lessonId,
    chapterId
  }
  sendMessage(JSON.stringify(msg))
}

const sendPlay = (lessonId: number, chapterId: number) => {
  const msg = {
    type: 0,
    lessonId,
    chapterId
  }
  sendMessage(JSON.stringify(msg))
}

const sendStop = (lessonId: number, chapterId: number) => {
  const msg = {
    type: 2,
    lessonId,
    chapterId
  }
  sendMessage(JSON.stringify(msg))
}

export default {
  connected,

  connect,
  close,
  setHeart,
  clearHeart,
  sendHeart,
  sendPlay,
  sendStop
}
